-- Spin Ride

local RIDE = {}

RIDE.NAME = "Spin-u-round"
RIDE.COST = 5
RIDE.DURATION = 15

function RIDE:Initialize()
	RIDE.motor = ents.FindByName("spin_rotor")[1]
	RIDE.obj = ents.FindByName("spin_obj")[1]:GetPhysicsObject()
	RIDE.door = ents.FindByName("spin_door")[1]
	RIDE.exit = ents.FindByName("spin_exit")[1]
	RIDE.queue = ents.FindByName("spin_queue")
	RIDE.toll = ents.FindByName("spin_screen")[1]
	RIDE:Stop()
	ents.FindByName("spin_gate")[1].RIDE = RIDE.NAME

end

function RIDE:GetScreen()
	return RIDE.toll
end

function RIDE:Start()
	print("Started")
	RIDE.door:Fire("Close","",0)
	RIDE:AlterSeats(true,false)
	RIDE.State = "Starting"
	RIDE.motor:Fire("turnon","",0)
	
	for k,v in pairs(RIDE.queue) do v:Fire("disable","",0) end
	 timer.Simple( RIDE.DURATION, function() RIDE:Stop() end )
end

function RIDE:Stop()
	print("Stopped")
	RIDE.State = "Stopping"
	RIDE.motor:Fire("turnoff","",0)
end

function RIDE:OnFullyStopped()
	RIDE.State = "Stopped"
	RIDE.door:Fire("Open","",0)
	RIDE:AlterSeats(false,true)
	
	for k,v in pairs(RIDE.queue) do v:Fire("enable","",0) end
end

function RIDE:AlterSeats(locked,kick)
	for k,v in pairs(ents.FindByName("spin_seat")) do
		if locked == true then 
			v:Lock()
		else 
			v:Unlock()
		end
		
		if kick == true then
			local driver = v.seat:GetDriver()
			if driver:IsValid() then 
				driver:ExitVehicle()
				driver:SetPos(RIDE.exit:GetPos())
				driver.Ticket = ""
			end
		end
	end
end

function RIDE:Think()
	if RIDE.State == "Stopping" && (RIDE.obj:GetAngleVelocity():Length() < 10) then
		RIDE:OnFullyStopped()
		RIDE.obj:AddAngleVelocity(Vector(0,0,0) - RIDE.obj:GetAngleVelocity())
	end
	
	RIDE.LastCheck = RIDE.LastCheck or CurTime()
	if (CurTime() > RIDE.LastCheck + 10)  && (RIDE.State == "Stopped") then
		RIDE.LastCheck = CurTime()
		RIDE.Wait()	
	end
end

function RIDE:Wait()
	local riding = 0
	for k,v in pairs(ents.FindByName("spin_seat")) do
		if v.seat:GetDriver():IsValid() then
			riding = riding + 1
		end
	end
	if riding != 0 then
		timer.Simple( riding * 10, function() RIDE:Start() end )
	end
end

GAMEMODE:AddRide(RIDE)